
package com.example.gorannet;

import static com.example.gorannet.CommonUtilities.SENDER_ID;
import static com.example.gorannet.CommonUtilities.displayMessage;

import com.google.android.gcm.GCMBaseIntentService;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.util.Log;

public class GCMIntentService extends GCMBaseIntentService
{

    private static final String TAG = "GCMIntentService";

    String [] ticket_array = new String [21];
    public GCMIntentService()
    {
        super(SENDER_ID);
    }

    /**
     * Method called on device registered
     **/
    @Override
    protected void onRegistered(Context context, String registrationId)
    {

        Log.i(TAG, "Device registered: regId = " + registrationId);
        displayMessage(context, "Your device registred with GCM", "");
        Log.d("NAME", MainActivity.name);
        ServerUtilities.register(context, MainActivity.name, MainActivity.email, registrationId);
    }

    /**
     * Method called on device un registred
     */
    @Override
    protected void onUnregistered(Context context, String registrationId)
    {
        Log.i(TAG, "Device unregistered");
        displayMessage(context, getString(R.string.gcm_unregistered), "");
        ServerUtilities.unregister(context, registrationId);
    }

    /**
     * Method called on Receiving a new message
     */
    @Override
    // inside GCMIntentService
    protected void onMessage(Context context, Intent intent)
    {
        try{

            DBHandler db = new DBHandler(getApplicationContext());
            long now = System.currentTimeMillis();

            if (intent.getExtras().getString("action").equals("insert"))
            {
                ticket_array[0] = intent.getExtras().getString("tctID");
                ticket_array[1] = intent.getExtras().getString("subject");
                ticket_array[2] = intent.getExtras().getString("telephone");
                ticket_array[3] = intent.getExtras().getString("status");
                ticket_array[4] = intent.getExtras().getString("priority");
                ticket_array[5] = intent.getExtras().getString("created_on");
                ticket_array[6] = intent.getExtras().getString("last_update");
                ticket_array[7] = intent.getExtras().getString("neihbor");
                ticket_array[8] = intent.getExtras().getString("alley");
                ticket_array[9] = intent.getExtras().getString("street");
                ticket_array[10] = intent.getExtras().getString("house");
                ticket_array[11] = "";
                ticket_array[12] = intent.getExtras().getString("site");
                ticket_array[13] = intent.getExtras().getString("pair");
                ticket_array[14] = intent.getExtras().getString("username");
                ticket_array[15] = intent.getExtras().getString("password");
                ticket_array[16] = intent.getExtras().getString("userID");
                ticket_array[17] = intent.getExtras().getString("assignedTo");
                ticket_array[18] = intent.getExtras().getString("conversation");
                ticket_array[19] = intent.getExtras().getString("posted");
                ticket_array[20] = intent.getExtras().getString("tctDet");
                db.insertTicketDetails(ticket_array);
                db.insertComments(ticket_array[0], ticket_array[20], ticket_array[18], "0", now);
            }
            //generateNotification(context, intent.getExtras().getString("tctDet"));
            //Error exist when update occurs
            if (intent.getExtras().getString("action").equals("update"))
            {
                String tct_id = intent.getExtras().getString("tctID");
                String status = intent.getExtras().getString("status");
                String priority = intent.getExtras().getString("priority");
                String conv = intent.getExtras().getString("conver");
                String comment = intent.getExtras().getString("tctDet");
                db.updateTicketDetails(tct_id, status,priority);
                db.insertComments(tct_id, comment, conv, "0", now);
            }

            displayMessage(context, intent.getExtras().getString("tctDet"), intent.getExtras().getString("tctID"));
            // notify user
            generateNotification(context, intent.getExtras().getString("status"));
        }
        catch(Exception e )
        {
        }
    }

    /**
     * Method called on receiving a deleted message
     */
    @Override
    protected void onDeletedMessages(Context context, int total)
    {
        Log.i(TAG, "Received deleted messages notification");
        String message = getString(R.string.gcm_deleted, total);
        displayMessage(context, message, "");

        // notifies user
        generateNotification(context, message);
    }

    /**
     * Method called on Error
     */
    @Override
    public void onError(Context context, String errorId)
    {
        Log.i(TAG, "Received error: " + errorId);
        displayMessage(context, getString(R.string.gcm_error, errorId), "");
    }

    @Override
    protected boolean onRecoverableError(Context context, String errorId)
    {
        // log message
        Log.i(TAG, "Received recoverable error: " + errorId);
        displayMessage(context, getString(R.string.gcm_recoverable_error, errorId), "");
        return super.onRecoverableError(context, errorId);
    }

    /**
     * Issues a notification to inform the user that server has sent a message.
     */
    static Context con;
    static Class<?> device = null;
    static Class<MyListItems> tablet = MyListItems.class;
    static Class<MyChoicesActivity> mobile = MyChoicesActivity.class;
    @SuppressWarnings("deprecation")
    private static void generateNotification(Context context, String message)
    {
        int icon = R.drawable.ic_launcher;
        long when = System.currentTimeMillis();

        NotificationManager notificationManager = (NotificationManager)context
                .getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = new Notification(icon, message, when);

        String title = context.getString(R.string.app_name);

        boolean deviceType = isTablet(context);
        if(deviceType == true){
            device = tablet;
        }else
            if(deviceType == false)
            {
                device = mobile;
            }


        Intent notificationIntent = new Intent(context, device);
        // set intent so it does not start a new activity
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent intent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
        notification.setLatestEventInfo(context, title, message, intent);
        notification.flags |= Notification.FLAG_AUTO_CANCEL;

        // Play default notification sound
        notification.defaults |= Notification.DEFAULT_SOUND;

        // notification.sound = Uri.parse("android.resource://" +
        // context.getPackageName() + "your_sound_file_name.mp3");

        // Vibrate if vibrate is enabled
        notification.defaults |= Notification.DEFAULT_VIBRATE;
        notificationManager.notify(1, notification);

    }
    //Determines If The Device is Tablet?!.....If it is Tablet it returns true
    public static boolean isTablet(Context context) {
        return (context.getResources().getConfiguration().screenLayout
                & Configuration.SCREENLAYOUT_SIZE_MASK)
                >= Configuration.SCREENLAYOUT_SIZE_LARGE;
    }

}
